const validate = require("validate.js");
const moment = require("moment");
const {formatResponse} = require("../utils/tool");
const {addReturnInfoDao, getReturnListDao, updateReturnDao} = require("../dao/returnSchoolDao");

// 关闭moment必须要使用的格式警告
moment.suppressDeprecationWarnings = true;

// 使用 datetime 必须添加 datetime 校验规则
validate.extend(validate.validators.datetime, {
    parse: function (value, options) {
        return +moment.utc(value);
    },
    format: function (value, options) {
        let format = options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD hh:mm:ss";
        return moment.utc(value).format(format);
    }
});

// 添加文章
module.exports.addReturnInfoService = async (returnInfo) => {
    const returnRule = {
        startTime: {
            presence: {
                allowEmpty: false
            },
            datetime: {
                earliest: moment.now(),
                message: "时间不能早于当前时间"
            }
        },
        endTime: {
            presence: {
                allowEmpty: false
            },
            datetime: true // datetime 不是 validate 中的 type 内置类型，而是一个独立的配置项
        },
        reason: {
            presence: {
                allowEmpty: false
            },
            type: "string",
        },
        isAgree: {
            presence: {
                allowEmpty: false
            },
            type: "integer",
            inclusion: [0, 1]
        },
        userId: {
            presence: {
                allowEmpty: false
            },
            type: "integer",
        },
        isHandle: {
            presence: {
                allowEmpty: false
            },
            type: "integer",
        }
    }
    try {
        await validate.async(returnInfo, returnRule);
        const result = await addReturnInfoDao(returnInfo)
        return formatResponse(0, '添加成功', result);
    } catch (error) {
        console.log(error)
        return formatResponse(1, '数据校验错误', error);
    }
}
// 分页获取返校信息
module.exports.getReturnListService = async (page, limit) => {
    const result = await getReturnListDao(page, limit);
    return formatResponse(0, '查询成功', result);
}
// 修改某个返校信息
module.exports.updateReturnService = async (id, returnInfo) => {
    const result = await updateReturnDao(id, returnInfo);
    return formatResponse(0, '修改成功', result);
}